<?php

namespace app\api\controller\ordertaker;

use app\admin\model\Evaluate;
use app\admin\model\Financialrecords;
use app\admin\model\Financialrecordsq;
use app\admin\model\join\Merchant;
use app\admin\model\store\Bank;
use app\admin\model\store\Withdrawal;
use app\api\model\JoinMerchant;
use app\api\model\JoinOnboarding;
use app\api\model\JoinSkill;
use app\api\model\User;
use app\common\controller\Api;
use think\Request;


class Ordertaker extends Api
{


//    protected $noNeedLogin = ['store_index','store_settings','store_information','login_passwords'];

    protected $order_taker_id;

    private  $user_token = '';


    private  $array_action=[];
    
    public function _initialize(Request $request = null)
    {


        //用户登录token
        $action=Request::instance()->action();

        $token=Request::instance()->header('token');
    
        $this->user_token=json_decode(base64_decode($token),1);
       
        

        if(!in_array($action,$this->array_action)){

            if(!$this->user_token){
               
                $this->success("未传token");

            }else{
                
                $this->order_taker_id=JoinOnboarding::where(['user_id'=>$this->user_token['user_id']])->value('id');
                
            }

        }
//

    }

    /**
     * @param Request $request
     * 骑手首页信息
     * ordertaker/ordertaker/rider_index
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function rider_index(Request $request)
    {

        $post=$request->post();
        $store=json_array(JoinOnboarding::where(['id'=>$this->order_taker_id])->field('id,name,avatar,star,my_commission,withdrawable,withdrawn,skill_ids,login_passwords')->find());
        // var_dump($store);die;
        if($store){
            $store['avatar']=yuming($store['avatar']);
        }
        //今日收益
        $store['today_money']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id])->sum('commission');
        //今日接单
        $store['today_count']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id])->count();
        //待入帐
        $store['to_be_credited']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id,'p_status'=>3])->count();

        //今日扣款
        $store['today_k_money']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id,'is_overtime'=>1])->sum('commission');
        //今日扣款接单
        $store['today_k_count']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id,'is_overtime'=>1])->count();
        //待扣款
        $store['to_be_deducted']=\app\api\model\Order::where(['q_user_id'=>$this->order_taker_id,'is_overtime'=>1,'is_deduction'=>0])->count();

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);
    }

    /**
     * 骑手修改技能
     * ordertaker/ordertaker/rider_skill
     * @param Request $request
     * @return \think\response\Json
     *
     */
     public  function rider_skill(Request $request)
     {
         $post=$request->post();

         $JoinOnboarding=JoinOnboarding::where(['id'=>$this->order_taker_id])->update(['skill_ids'=>$post['skill_ids']]);
         if($JoinOnboarding){
              return json(['code'=>200,'msg'=>'修改成功']);
         }else{
              return json(['code'=>404,'msg'=>'修改失败，请稍后再试']);
         }
     }

    /**
     * 骑手技能列表
     * ordertaker/ordertaker/skill_list
     * @param Request $request
     * @return \think\response\Json
     *
     */
    public  function skill_list(Request $request)
    {
        $post=$request->post();

        $JoinOnboarding=json_array(JoinSkill::field('id,name')->select());

        return json(['code'=>200,'msg'=>'修改成功','data'=>$JoinOnboarding]);

    }


//    /**
//     * @param Request $request
//     * 店铺设置
//     * api/store/store/store_settings
//     * @return \think\response\Json|void
//     * @throws \think\Exception
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\ModelNotFoundException
//     * @throws \think\exception\DbException
//     */
//    public function store_settings(Request $request)
//    {
//        $post=$request->post();
//        if($post['type']==1){
//            $store=Merchant::where(['id'=>$post['store_id']])->field('id,trade_name,avatar,phone,join_type_id,address')->find()->toArray();
//            if($store){
//                $store['avatar']=yuming($store['avatar']);
//            }
//            return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);
//        }
//        if($post['type']==2){
//            $data=[
//                'trade_name'=>$post['trade_name'],
//                'avatar'=>$post['avatar'],
//                'phone'=>$post['phone'],
//                'join_type_id'=>$post['join_type_id'],
//                'address'=>$post['address'],
//            ];
//            $insert=Merchant::where(['id'=>$post['store_id']])->update($data);
//            if($insert){
//                return  json(['code'=>200,'msg'=>'修改成功','data'=>'']);
//            }else{
//                return  json(['code'=>200,'msg'=>'暂无修改','data'=>'']);
//            }
//        }
//    }

    /**
     * @param Request $request
     * 我的-设置-骑手信息
     * ordertaker/ordertaker/store_information
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function store_information(Request $request)
    {
        $post=$request->post();
        $store=JoinOnboarding::where(['id'=>$this->order_taker_id])->field('id,name,phone,id_card_front_image,id_card_back_image,skill_ids')->find()->toArray();

        $store['skill_ids']=json_array(JoinSkill::where(['id'=>['in',$store['skill_ids']]])->select());

        if($store['skill_ids']){
            $store['skill_ids']=array_column($store['skill_ids'],'name');
        }
        if($store){
            $store['id_card_front_image']=yuming($store['id_card_front_image']);
            $store['id_card_back_image']=yuming($store['id_card_back_image']);
        }
        return  json(['code'=>200,'msg'=>'请求成功','data'=>$store]);

    }

    /**
     * @param Request $request
     * 我的-设置-登录密码已设置
     * ordertaker/ordertaker/login_passwords
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login_passwords(Request $request)
    {
        $post=$request->post();
        $store=JoinOnboarding::where(['id'=>$this->order_taker_id])->find()->toArray();
        if($store['login_passwords']!=md5(md5($post['y_password']))){
            return  json(['code'=>404,'msg'=>'原密码错误']);
        }
        if($post['password']!=$post['q_password']){
            return  json(['code'=>404,'msg'=>'修改密码与确认密码不一致']);
        }
        $up=JoinOnboarding::where(['id'=>$this->order_taker_id])->update(['login_passwords'=>md5(md5($post['password']))]);
        if($up){
            return  json(['code'=>200,'msg'=>'已修改','data'=>'']);
        }
    }

    /**
     * @param Request $request
     * 我的-设置-登录密码未设置
     * ordertaker/ordertaker/login_set
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login_set(Request $request)
    {

        $post=$request->post();
        $code=200;
//        $store=JoinMerchant::where(['id'=>$this->store_id])->find()->toArray();
        if($code!=$post['code']){
            return  json(['code'=>404,'msg'=>'验证码错误']);
        }
        if($post['q_password']!=$post['password']){
            return  json(['code'=>404,'msg'=>'修改密码与确认密码不一致']);
        }
        $up=JoinOnboarding::where(['id'=>$this->order_taker_id])->update(['login_passwords'=>md5(md5($post['password']))]);
        if($up){
            return  json(['code'=>200,'msg'=>'已设置','data'=>'']);
        }
    }

    /**
     * @param Request $request
     * 我的-设置-发送验证码
     * ordertaker/ordertaker/send_verification_code
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send_verification_code(Request $request)
    {
        $this->success("暂未设置");
        $mobile=$request->post('mobile');
        if (\sms\Sms::sendCode($mobile)) {
            $this->success("发送成功");
        }
    }

//    /**
//     * 绑定银行卡
//     * store/store/add_bank_card
//     * @param Request $request
//     * @return \think\response\Json|void
//     * @throws \think\Exception
//     * @throws \think\db\exception\DataNotFoundException
//     * @throws \think\db\exception\ModelNotFoundException
//     * @throws \think\exception\DbException
//     *
//     */
//    public function add_bank_card(Request $request)
//    {
//        $POST=$request->post();
//        $find=Bank::where(['bank_card_number'=>$POST['bank_card_number'],'store_id'=>$this->store_id])->find()->toArray();
//        if($find){
//            return  json(['code'=>404,'msg'=>'该银行卡已绑定','data'=>'']);
//        }
//        $data=[
//            'name'=>$POST['name'],
//            'bankid'=>$POST['bankid'],
//            'bankname'=>$POST['bankname'],
//            'bank_card_number'=>$POST['bank_card_number'],
//            'mobile'=>$POST['mobile'],
//            'user_id'=>$this->auth->id,
//            'store_id'=>$this->store_id,
//            'createtime'=>time()
//        ];
//        $in=Bank::create($data);
//        if($in){
//            return  json(['code'=>200,'msg'=>'添加成功','data'=>'']);
//        }
//    }
//
//
//    /**
//     * 开户银行列表
//     * store/store/bank_list
//     * @param Request $request
//     * @return \think\response\Json|void
//     * @throws \think\exception\DbException
//     *
//     */
//    public  function  bank_list(Request $request)
//    {
//        $POST=$request->post();
//        $bank= \app\admin\model\Bank::where(['switch'=>1])->select();
//        if($bank){
//            $bank=$bank->toArray();
//            foreach ($bank as &$value){
//                $value['image']=yuming($value['image']);
//            }
//        }
//        return  json(['code'=>200,'msg'=>'请求成功','data'=>'']);
//
//
//    }


    /**
     * 数据统计
     * ordertaker/ordertaker/rider_statistics
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     *
     */
    public  function  rider_statistics(Request $request)
    {
        $post=$request->post();
        $where['q_user_id']=$this->order_taker_id;
        if($post['type']==1){
            $start=strtotime($post['start']);
            $end=strtotime($post['end']);
            $where['createtime']=['between', [$start, $end,'AND']];
        }
        if($post['type']==2){
            $start=strtotime($post['start']);
            $end=strtotime($post['end']);
            $where['createtime']=['between', [$start, $end,'AND']];
        }

        //收益统计

        //今日收益
        $data['revenue_statistics']['today_money']=\app\api\model\Order::where($where)->where(['is_deduction'=>0])->sum('commission');
        //昨日全天
        $data['revenue_statistics']['yesterday_money']=\app\api\model\Order::whereTime('createtime','yesterday')->where(['is_deduction'=>0])->sum('commission');
        //昨日此刻
        $data['revenue_statistics']['yesterday_cs_money']=\app\api\model\Order::where($where)->where(['is_deduction'=>0])->sum('commission');

        //接单笔数
        $data['revenue_statistics']['number_of_orders_received']=\app\api\model\Order::where($where)->count();
        //待入帐
        $data['revenue_statistics']['to_be_credited']=\app\api\model\Order::where($where)->where(['p_status'=>3])->sum('commission');
        //已完成
        $data['revenue_statistics']['completed']=\app\api\model\Order::where($where)->where(['p_status'=>4])->sum('commission');
        //待完成
        $data['revenue_statistics']['to_be_completed']=\app\api\model\Order::where($where)->where(['p_status'=>['in','1,2,3']])->sum('commission');
        //客单价
        if($data['revenue_statistics']['number_of_orders_received']>0){
            $data['revenue_statistics']['customer_unit_price']=$data['revenue_statistics']['today_money']/$data['revenue_statistics']['number_of_orders_received'];
        }else{
            $data['revenue_statistics']['customer_unit_price']=0;
        }


        //售后统计

        //今日退款
        $data['after_sales_statistics']['todays_refund']=\app\api\model\Order::where($where)->where(['is_deduction'=>1])->sum('deduction');
        //昨日全天
        $data['after_sales_statistics']['refund_yesterday']=\app\api\model\Order::whereTime('createtime','yesterday')->where(['is_deduction'=>1])->sum('deduction');;
        //昨日此刻
        $data['after_sales_statistics']['yesterday_at_this_moment']=\app\api\model\Order::where($where)->where(['is_deduction'=>1])->sum('deduction');

        //扣款订单数
        $data['after_sales_statistics']['number_of_refunds']=\app\api\model\Order::where($where)->where(['is_deduction'=>1])->count();
        //待扣款订单数
        $data['after_sales_statistics']['Number_of_count']=\app\api\model\Order::where($where)->where(['is_deduction'=>0])->count();
        //待扣款金额
        $data['after_sales_statistics']['pending_refund']=\app\api\model\Order::where($where)->where(['is_deduction'=>1])->sum('deduction');
        //客单价
        if($data['after_sales_statistics']['number_of_refunds']>0){
            $data['after_sales_statistics']['customer_unit_price']=$data['after_sales_statistics']['todays_refund']/$data['after_sales_statistics']['number_of_refunds'];
        }else{
            $data['after_sales_statistics']['customer_unit_price']=0;
        }

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
    }


    /**
     * 骑手评价列表
     * ordertaker/ordertaker/shop_evaluation_reply
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shop_evaluation_reply(Request $request)
    {
        $post=$request->post();
        $pagesize=$request->post('pagesize',10);
        $Evaluate=Evaluate::where(['q_user_id'=>$this->order_taker_id])
            ->field('id,user_image,user_name,start,content,images,createtime,store_content')
            ->page($post['page'],$pagesize)
            ->order('createtime desc')
            ->select();
        $toal=Evaluate::where(['q_user_id'=>$this->order_taker_id])->count();
        foreach ($Evaluate as &$value){
            $value['user_image']=yuming($value['user_image']);
            $value['images']=yuming(explode(',',$value['images']),'');
            $value['createtime']=date('Y-m-d hH:i:s)',$value['createtime']);
        }

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$Evaluate,'toal'=>$toal]);
    }

    /**
     * @return void
     *
     *  骑手钱包金额
     *  ordertaker/ordertaker/my_wallet
     */
    public function my_wallet(Request $request){

        $data=json_array(JoinOnboarding::where(['id'=>$this->order_taker_id])->field('id,my_commission,withdrawable,withdrawn')->find());

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
    }

    /**
     * 骑手资产列表
     * ordertaker/ordertaker/financialrecords_list
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function  financialrecords_list(Request  $request){
        $post=$request->post();
        $data=json_array(Financialrecordsq::where(['q_user_id'=>$this->order_taker_id])
            ->field('id,money,type,title,order,createtime')
            ->page($post['page'],$post['pagesize'])
            ->order('createtime desc')
            ->select());
        $toal=Financialrecordsq::where(['q_user_id'=>$this->order_taker_id])->count();
        if($data){
            foreach ($data as &$value){
                $value['createtime']=date('Y-m-d H:i:s',$value['createtime']);
            }
        }

        return  json(['code'=>200,'msg'=>'请求成功','data'=>$data,'toal'=>$toal]);

    }

    /**
     * 骑手提现
     * ordertaker/ordertaker/rider_withdrawal
     * @param Request $request
     * @return \think\response\Json|void
     * @throws \think\Exception
     *
     */
    public function rider_withdrawal(Request  $request){
        $post=$request->post();
        $JoinOnboarding=json_array(JoinOnboarding::where(['id'=>$this->order_taker_id])->find());
        if($post['money']<1){
            return  json(['code'=>200,'msg'=>'提现金额必须大于0','data'=>'']);
        }
        if($JoinOnboarding['withdrawable']<$post['money']){
            return  json(['code'=>200,'msg'=>'余额不足','data'=>'']);
        }
        $data=[
            'user_id'=>$this->auth->id,
            'q_user_id'=>$this->order_taker_id,
            'money'=>$post['money'],
            'createtime'=>time(),
        ];
        $data=\app\admin\model\Withdrawal::create($data);
        $setDec=JoinOnboarding::where(['id'=>$this->order_taker_id])->setDec('withdrawable',$post['money']);
        $setInc=JoinOnboarding::where(['id'=>$this->order_taker_id])->setInc('withdrawn',$post['money']);
        if($data&&$setDec&&$setInc){
            return  json(['code'=>200,'msg'=>'提交成功，等待后台审核','data'=>'']);
        }
    }

}